import { getInfo, login } from '@/api/user'

const state = {
  token: localStorage.getItem('token') || '',
  userInfo: null
}

const mutations = {
  setToken(state, token) {
    localStorage.setItem('token', token)
    state.token = token
  },
  setUser(state, user) {
    state.userInfo = user
  },
  removeToken(state) {
    localStorage.removeItem('token')
    state.token = ''
  },
  removeUserInfo(state) {
    state.userInfo = null
  }
}

const actions = {
  async login({ commit }, data) {
    const { jwt, user } = await login(data)
    commit('setToken', jwt)
    commit('setUser', user)
  },
  async getInfo({ commit }) {
    commit('setUser', await getInfo())
  },
  logout({ commit }) {
    commit('removeToken')
    commit('removeUserInfo')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
